<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-preview="handlePreview"
      :file-list="fileList"
      :limit="limit"
      :accept="accept"
      :auto-upload="false"
      :http-request="httpRequest"
    >
      <el-button slot="trigger" size="small" class="iconfont icon-daoruexcel">
        <i style="margin-right: 3px"></i>导入Excel
      </el-button>
      <el-button
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click="submitUpload"
        >上传Excel</el-button
      >
      <div slot="tip" class="el-upload__tip">只 能 上 传 xlsx / xls 文 件</div>
    </el-upload>
    <el-dialog :visible.sync="visible" width="800px" title="excel导入">
      <el-table
        border
        size="small"
        :data="tableData"
        height="450"
        style="width: 100%"
      >
        <el-table-column
          :show-overflow-tooltip="true"
          v-for="(key, value) in filterVal"
          :key="key"
          :prop="value"
          :label="key"
        ></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
/*
  导入Excel组件
  接收一个对象 filterVal,且必填
  对象的key是你表格的字段名,对应的value是excel表格需要对应的表头名
  例如 网页表格中字段名为 id和name,对应的excel表头名为ID和名称
  那么 const filterVal={id: "ID",name: "名称"}
  通过绑定事件 getExcel 获取后台返回的数据(res)及本地导入的数据(data)
  */
const Address = require("../utils/url");
export default {
  name: "ExcelIn",
  props: {
    filterVal: {
      type: Object,
      required: false
    },
    action: {
      type: String,
      default: Address.UPLOAD, //默认值
      required: false
    }
  },
  data() {
    return {
      fileList: [],
      tableData: [],
      limit: 1,
      accept:
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel",
      fileTemp: null,
      visible: false
    };
  },
  methods: {
    httpRequest(param) {
      // console.log(param)
    },
    //预览
    handlePreview(file) {
      this.visible = false;
    },
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      this.fileList = fileList;
      const fileType = file.raw.name.substring(
        file.raw.name.lastIndexOf(".") + 1
      );
      if (this.fileTemp) {
        if (fileType === "xlsx" || fileType === "xls") {
          this.importf(this.fileTemp);
        } else {
          this.$notify({
            title: "警告",
            message: "附件格式错误，请删除后重新上传！",
            type: "warning"
          });
        }
      } else {
        this.$notify({
          title: "警告",
          message: "请上传附件！",
          type: "warning"
        });
      }
    },
    handleRemove(file, fileList) {
      this.fileTemp = null;
      const obj = {
        res: {}, //后台返回的数据
        data: [] //导入excel表格的数据
      };
      // this.$emit('getExcel', obj);
      // console.log("删除了");
    },
    handleSuccess(response, file, fileList) {
      let formData = new FormData();
      formData.append("file", file);
      // console.log(formData.get("file"));
      const obj = {
        res: formData, //后台返回的数据
        data: this.tableData //导入excel表格的数据
      };
      this.$emit("getExcel", obj);
    },
    importf(obj) {
      const _this = this;
      const rABS = false; //是否将文件读取为二进制字符串
      const f = obj; //通过DOM取文件数据
      const reader = new FileReader();
      FileReader.prototype.readAsBinaryString = function(f) {
        const rABS = false; //是否将文件读取为二进制字符串
        const reader = new FileReader();
        let binary = "";
        let wb; //读取完成的数据
        let outdata;
        reader.onload = function(e) {
          const bytes = new Uint8Array(reader.result);
          const length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          let XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          const arr = [];
          outdata.map(item => {
            const obj = {};
            for (let key1 in _this.filterVal) {
              for (let key2 in item) {
                if (_this.filterVal[key1] === key2) {
                  obj[key1] = item[key2];
                }
              }
            }
            arr.push(obj);
          });
          _this.tableData = [...arr];
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    submitUpload() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped></style>
